package com.cy.cy2025.activity

import android.hardware.Camera
import android.os.Bundle
import android.os.Environment
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.bumptech.glide.Glide
import com.cy.cy2025.databinding.ActivityCameraTestBinding
import com.cy.cy2025.util.LogUtil
import com.cy.cy2025.util.PermissionUtil
import com.cy.cy2025.util.PermissionsCallback
import com.cy.cy2025.util.ToastUtil
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.io.File

class CameraTestActivity : AppCompatActivity() {

    val binding by lazy { ActivityCameraTestBinding.inflate(layoutInflater) }

    var started = false
    var cameraId: Int = Camera.CameraInfo.CAMERA_FACING_BACK
    val pictureSavaDir by lazy { getExternalFilesDir(Environment.DIRECTORY_PICTURES)?.path+"/" }
    var pictureSavaPath = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)

        binding.btnStart.setOnClickListener {
            if (!started){
                PermissionUtil.requestPermissions(object : PermissionsCallback {
                    override fun onSuccess() {
                        // 启动相机开始预览
                        started = true
                        startCamera()
                    }

                    override fun onFailure(
                        failures: List<String>,
                        forbiddings: List<String>
                    ) {
                        ToastUtil.showShort("权限获取失败")
                    }
                },android.Manifest.permission.CAMERA,android.Manifest.permission.RECORD_AUDIO)
            }
        }

        binding.btnGet.setOnClickListener {
            pictureSavaPath = pictureSavaDir + System.currentTimeMillis() + ".jpg"
            binding.cameraView.takePicture(pictureSavaPath,true){
                val file = File(pictureSavaPath)
                LogUtil.i("拍照成功", "${file.path} >> ${file.length()}")
                Glide.with(this@CameraTestActivity).load(pictureSavaPath).into(binding.imageView)
            }
        }

        binding.btnSwitch.setOnClickListener {
            switchCamera()
        }
    }


    private fun startCamera() {
        // 启动相机预览
        binding.cameraView.startPreview()
    }

    private fun switchCamera() {
        binding.cameraView.switchCamera()
    }
}